var web = web || {};
web.Friends = Class.create();
web.Friends.prototype = {
	initialize: function() {
		this.element = null;
		this.settings = {};
		this.tips = null;
		this.selected = null;
		this.container = null;
		this.input = null;
		this.inputSel = null;
		this.popup = null;
		this.auto = null;
		this.lastLi = null;
		this.viewer = null;
		this.pages = null;
		this.status = null;
		this.toShow = [];
		this.toSelected = [];
	},
	setObject: function(popup, auto) {
		this.popup = popup;
		this.auto = auto;
	},
	bind: function(element_id, settings) {
		var _this = this;
		var _element = $('#'+ element_id);
		if( 0 == _element.size() ) return;
		
		var _settings = $.extend({
			maxSel: 0,
			inSelId:''
		}, settings);
		
		if (''==_settings.inSelId) return;
		_element.bind('click', {element:_element, setting:_settings}, function(event) {
			_this._init(event.data.element, event.data.setting);
		});
		_element.children("a").bind('click', {element:_element, setting:_settings}, function(event) {
			_this._init(event.data.element, event.data.setting);
		});		
		this._bindEvent(_element);
	},
	_getElement: function(element) {
		this.element = element;
		this.selected  = this.element.children("a");
		this.container = this.element.find("ul");
		this.input = this.element.find("input");
		this.lastLi = this.container.find("li:last");
	},
	_autoFindData: function() {
		var _val = this.auto._getInputVal();
		if (''==_val) return;
		
		var _find = false;
		this.auto._clearList();
		for(var i=0; i<g_globals.friend.list.length; i++) {
			if (this.auto._isShowLimit()) break;
			if(g_globals.friend.list[i][2].indexOf(_val) === 0 || g_globals.friend.list[i][3].indexOf(_val) === 0 || g_globals.friend.list[i][4].indexOf(_val) === 0) {
				this.auto._addList($('<a href="javascript:{};"><span>'+ g_globals.friend.list[i][2] +'</span>'+ g_globals.friend.list[i][3] +'</a>'), g_globals.friend.list[i][0]);
				_find = true;
			}
		}
		
		if (_find) this.auto._show();
		else  this.auto._hide();
	},
	_bindEvent: function(_element) {
		var _this = this;
		this._getElement(_element);
		
		this.auto.bind(this.element.attr('id'), {inId:this.input.attr('id'),maxShow:5, msg:'输入好友姓名/拼音或按↑↓键选择', getData:function() {
			_this._hideTips();
			if (g_globals.friend) {
				_this._autoFindData();
			} else {
				$.getJSON("http://old.sns.com/member/ajax_friend.php?op=friend_select_data2&jsoncallback=?", function(data){
					g_globals.friend = data;
					_this._autoFindData();
				});
			}
		},
		setData:function(v) {
			if (_this._isSelectedLimit()) {
				_this.auto._setInputVal('');
				return;
			}
			
			_this._addSelected(v);
			_this._setSelectedFriendOne(v);
			_this.auto._setInputVal('');
		}});
		
		this.popup.bind(this.selected.attr('id'), {id:'popup_panel_friend_selecter',title:'选择好友', width:705, data:function(){
			var _popup = this;
			if (!_popup._isLoaded()) {
				$.getJSON("http://old.sns.com/member/ajax_friend.php?op=friend_select_ui2&jsoncallback=?", function(data){
					_popup._setPopupBody(data.ui);
					_this.viewer = _popup._popupBodyFind("#friend_list");
					_this.pages = _popup._popupBodyFind("#friend_pages");
					_this.status = _popup._popupBodyFind("#friend_status");
					
					var _input = _popup._popupBodyFind("#friend_find");
					_input.bind({
						keyup: function() {
							_this._findFriendByInput(this);
						},
						click:function() {
							var _self = $(this);
							if (!_self.attr('val')) _self.attr('val', _self.val());
							_self.val('');
							_self.removeClass('hint');
						},
						blur:function() {
							var _self = $(this);
							var _val = _self.val();
							if (''==_val) {
								_self.val(_self.attr('val'));
								_self.addClass('hint');
							}
						}
					});
					
					var _select = _popup._popupBodyFind("#friend_group");
					_select.bind('change', function() {
						_this._findFriendByGroup(this);
					});
					
					var _ok = _popup._popupBodyFind("#button_ok");
					_ok.bind('click', function() {
						_this._setSelectedFriends();				   
						_popup._hide();
					});
					
					var _cannel = _popup._popupBodyFind("#button_cannel");
					_cannel.bind('click', function() {
						_popup._hide();
					});
					
					if (g_globals.friend) {
						_this.toShow = g_globals.friend.list;
						_this._showFriendList(1);
						_this._showSelectedInfo();
						return false;
					}
					
					$.getJSON("http://old.sns.com/member/ajax_friend.php?op=friend_select_data2&jsoncallback=?", function(data){
						g_globals.friend = data;
						_this.toShow = data.list;
						_this._initFriendGroup(_select.get(0));
						_this._showFriendList(1);
						_this._showSelectedInfo();
					});
				});
			} else {
				_this.toShow = g_globals.friend.list;
				_this._showFriendList(1);
				_this._showSelectedInfo();
			}
		}});
		
		this.input.bind({
			focus: function() {_this._showTips();},
			blur: function() {_this._hideTips();}
		});
	},
	_init: function(element, settings) {
		var _this = this;
		this._getElement(element);
		this.settings = settings;
		this.inputSel = $('#'+this.settings.inSelId);
		if (0==this.inputSel.size()) return;
		this.toSelected = this._getSelectedFriends();
		this.input.focus();
	},
	_showTips: function() {
		if (null==this.tips) this._createTips();
		var _offset = this.element.offset();
		this.tips.css({left:_offset.left, top:_offset.top+this.element.height()+3, width:this.element.width()});
		this.tips.show();
	},
	_hideTips: function() {
		this.tips.hide();
	},
	_createTips: function() {
		this.tips = $('<div class="input_friend_select_tips"><p>请输入好友姓名(支持拼音首字母)或点击右边的图标进行选择</p></div>');
		this.tips.appendTo(document.body);
	},
	_initFriendGroup: function(selecter) {
		for(var i=0; i<g_globals.friend.group.length; i++) {
			selecter.options[i+1] = new Option(g_globals.friend.group[i][1], g_globals.friend.group[i][0]);
		}
	},
	_findFriendByGroup: function(selecter) {
		if (!g_globals.friend) return;
		this.toShow = [];

		var _val = selecter.options[selecter.selectedIndex].value;
		if(_val == 0) {
			this.toShow = g_globals.friend.list;
		} else {
			for(var i=0; i<g_globals.friend.list.length; i++) {
				if(g_globals.friend.list[i][1] == _val) {
					this.toShow.push(g_globals.friend.list[i]);
				}
			}
		}
			
		this._showFriendList(1);	
	},
	_findFriendByInput: function(input) {
		if (!g_globals.friend) return;
		var _val = input.value;
		this.toShow = [];
		
		if (''==_val) {
			this.toShow = g_globals.friend.list;
		} else {
			for(var i=0; i<g_globals.friend.list.length; i++) {
				if(g_globals.friend.list[i][2].indexOf(_val) === 0 || g_globals.friend.list[i][3].indexOf(_val) === 0 || g_globals.friend.list[i][4].indexOf(_val) === 0) {
					this.toShow.push(g_globals.friend.list[i]);
				}
			}
		}
		this._showFriendList(1);	
	},
	_showFriendList: function(page) {
		var _this = this;
		var _total = this.toShow.length; 
		this.viewer.empty();
		if (0==_total) {
			this.viewer.html('<center style="padding:20px 0px 20px 0px;"><font color="#FF0000">没有找到符合条件的好友</font></center>');
			return;
		}
		
		var _pageSize = 10;
		var _offset = (page-1)*_pageSize;
		var _end = _offset+_pageSize;
		var _user,_class;
		for (var i=_offset; i<_end; i++) {
			if (i>=_total) break;
			_class = 'thumb_wrap';
			if (this._isSelected(this.toShow[i][0])) _class = 'thumb_wrap view_selected';
			_user =$('<div class="'+ _class +'" uid="'+ this.toShow[i][0] +'"><div class="thumb"><img src="http://pic.kaixin001.com/logo/11/76/50_'+ this.toShow[i][0] +'_1.jpg" /></div><span>'+ this.toShow[i][2] +'</span></div>');
			_user.appendTo(this.viewer);
			_user.bind({
				mouseover:function(){$(this).addClass('view_over');},
				mouseout:function(){$(this).removeClass('view_over');},
				click:function(){
					var _self = $(this);
					var _uid = _self.attr('uid');
					
					if (_self.hasClass('view_selected')) {
						_self.removeClass('view_selected');
						_this._removeSelected(_uid);
					} else {
						if(!_this._isSelectedLimit()) {
							_self.addClass('view_selected');
							_this._addSelected(_uid);
						}
					}
					_this._showSelectedInfo();
				}
			});
		}
		
		this._showPages(_total, _pageSize, page);
		this.popup._centerAlign();
	},
	_showPages: function(total, size, page) {
		var _this = this;
		this.pages.empty();
		if( total <= size ) return;
		
		var _totalPage = Math.ceil(total/size);
		var _pages = $('<div class="friend_pages"></div>');
		var _a;
		
		if (page>1) {
			_a = $('<a href="javascript:{};">< 上一页</a>');
			_a.appendTo(_pages);
			this._bindPageEvent(_a, page-1);
		}
		
		for(var i=1; i<=_totalPage; i++) {
			if (page==i) _a = $('<a class="cur">'+ i +'</a>');
			else _a = $('<a href="javascript:{};">'+ i +'</a>');
			_a.appendTo(_pages);
			this._bindPageEvent(_a, i);
		}
		
		if (page<_totalPage) {
			_a = $('<a href="javascript:{};">下一页 ></a>');
			_a.appendTo(_pages);
			this._bindPageEvent(_a, page+1);
		}
		this.pages.append(_pages);
	},
	_bindPageEvent: function(a, num) {
		var _this = this;
		a.bind('click', {n: num}, function(event) {
			_this._showFriendList(event.data.n);
		});
	},
	_isSelectedLimit: function() {
		if (0!=this.settings.maxSel && this.toSelected.length >= this.settings.maxSel) return true;
		else return false;
	},
	_addSelected: function(uid) {
		this.toSelected.push(uid);
	},
	_removeSelected: function(uid) {
		var _length = this.toSelected.length;
		for (var i=0; i<_length; i++) {
			if (uid == this.toSelected[i]) {
				this.toSelected.splice(i, 1);
				break;
			}
		}
	},
	_isSelected: function(uid) {
		var _find = false;
		var _length = this.toSelected.length;
		for (var i=0; i<_length; i++) {
			if (uid == this.toSelected[i]) {
				_find = true;
				break;
			}
		}
		return _find;
	},
	_showSelectedInfo: function() {
		var _length = this.toSelected.length;
		var _status = '';
		if( this.settings.maxSel > 0 ) {
			_status = '最多可选 <span>'+ this.settings.maxSel +'</span> 位好友，';
		}
		_status += '当前已选择了 <span>'+ _length +'</span> 位好友';
		this.status.html(_status);
	},
	_getSelectedFriends: function() {
		var _val = this.inputSel.val();
		if (''==_val) return [];
		return _val.split(',');
	},
	_setSelectedFriendOne: function(uid) {
		var _this = this;
		var _li,_user,_em;
		_user = this._getFriendInfo(uid);
		_li = $('<li uid="'+ _user[0] +'"><a href="javascript:{};"><span>'+ _user[2] +'<em class="x" title="移除"></em></span></a></li>');
		this.lastLi.before(_li);
		
		_em = _li.find("em");
		_em.bind('click', {li: _li}, function(event) {
			_this._delSelectedFriendOne(event.data.li);
			return false;
		});
		_em.bind({
			mouseover:function(){var _self=$(this); _self.removeClass(); _self.addClass('xx');},
			mouseout:function(){var _self=$(this); _self.removeClass(); _self.addClass('x');}
		});
		
		var _val = this.inputSel.val();
		if (''==_val) this.inputSel.val(uid);
		else this.inputSel.val(_val +','+ uid);
	},
	_delSelectedFriendOne: function(li) {
		var _uid = li.attr('uid');
		this._removeSelected(_uid);
		li.remove();
		
		if (this.toSelected.length>0) this.inputSel.val(this.toSelected.join(','));
		else this.inputSel.val('');
	},
	_setSelectedFriends: function() {
		var _length = this.toSelected.length;
		if (0==_length) return;
		
		this.container.children().remove("li[uid]");
		this.inputSel.val('');
		
		for (var i=0; i<_length; i++) {
			this._setSelectedFriendOne(this.toSelected[i]);
		}
	},
	_getFriendInfo: function(uid) {
		var _length = g_globals.friend.list.length;
		for (var i=0; i<_length; i++) {
			if (uid == g_globals.friend.list[i][0]) return g_globals.friend.list[i];
		}
		return [];
	},
	debug: function(str) {
		var debug = $('#span_debug');
		debug.html(debug.html() +"\n"+ str);
	}
}